import base64
import json

import requests
from Crypto.Cipher import AES
from app.exception import APIException, SERVER_ERROR


class Weixin(object):
    def __init__(self, app=None):
        self.appid = None
        self.secret = None
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        self.appid = app.config['WX_APPID']
        self.secret = app.config['WX_SECRET']

    def jscode2session(self, js_code):
        req_params = {
            "appid": self.appid,  # 小程序的 ID
            "secret": self.secret,  # 小程序的 secret
            "js_code": js_code,
            "grant_type": 'authorization_code'
        }
        # r = requests.get('https://api.weixin.qq.com/sns/jscode2session', params=req_params)
        try:
            r = requests.get('https://api.weixin.qq.com/sns/jscode2session', params=req_params)
        except Exception as e:
            print(e)
        print(r)
        return r.json()

    def decrypt(self, session_key, encrypted_data, iv):
        # base64 decode
        session_key = base64.b64decode(session_key)
        encrypted_data = base64.b64decode(encrypted_data)
        iv = base64.b64decode(iv)

        cipher = AES.new(session_key, AES.MODE_CBC, iv)

        decrypted = json.loads(self._unpad(cipher.decrypt(encrypted_data)))

        if decrypted['watermark']['appid'] != self.appid:
            raise APIException(SERVER_ERROR)

        return decrypted

    def _unpad(self, s):
        return s[:-ord(s[len(s)-1:])]